import {
  Databasetitle,
  Databasesort_rules,
  DataBasetRelease_items,
  DatabaseList,
  Databasetfavorites,
  deleteDatabasetfavorites,
  DataBasetexport
} from '@/api/Database'

import { Button, notification, Modal, Rate, Typography, Tooltip, Checkbox } from 'antd'

import { export_daily_counts } from '@/api/common'

import { SwapOutlined } from '@ant-design/icons'

import { HsAdminProTable } from '@hs-admin/base-components'

import { getItem, handleTableShowDate, message, PERMISSIONS } from '@hs-admin/utils'

import { useImmer } from 'use-immer'

const { Text } = Typography

import { useState, useRef, useEffect, memo, forwardRef, useImperativeHandle } from 'react'

import { ServerEmailModal } from '@hs-server/components'

const RelationList = (props: any, ref: any) => {
  const { success, sorterItem, Inputsearch, searchValue, hasInit, relation } = props
  //导出提示栏
  const [api, contextHolder] = notification.useNotification()

  //勾选的Keys
  const [selectedRowKeys, setselectedRowKeys]: any = useState([])

  //列表counts
  const [counts, setcounts] = useState(0)

  //导出邮箱ref
  const EmailModalRef = useRef<any>(null)

  //导出数量超出5000 小于一万限制弹框
  const [isModalOpen2, setModalOpen2] = useState(false)

  //查询关联数据的弹框
  const [isModalOpen1, setisModalOpen1] = useState(false)

  //关联数据列表
  const [release_items, setrelease_items] = useState([])

  //储存选中的右边列表的id传给左边筛选组件
  const [Associationid, setAssociationid]: any = useState([])

  //列表的columns
  const [columns, setColumns]: any = useState([])

  //列表数据
  const [data, setData] = useState([])

  //列表表头
  const [columnsStateMap, setColumnsStateMap]: any = useState({})

  const [columnsChangeFlag, setcolumnsChangeFlag] = useState(true)

  const actionRef: any = useRef()

  const baseConfig = {
    title: '操作',
    dataIndex: 'action',
    render: (_name: any, row: any) => (
      <div className="flex items-center">
        <Tooltip placement="topLeft" title={'关联查询'}>
          <div
            onClick={() => {
              setAssociationid([])
              openModal(row.id)
            }}>
            {relation && <SwapOutlined className="mx-10px" />}
          </div>
        </Tooltip>
        <Tooltip placement="topLeft" title={row.is_favorite ? '取消收藏' : '收藏'}>
          <Rate count={1} value={row.is_favorite ? 1 : 0} onChange={() => ChangeRate(row)} />
        </Tooltip>
      </div>
    ),
    width: 90
  }

  // 查询导出数量
  const export_counts = () => {
    export_daily_counts().then((res: any) => {
      res.daily_count = res.daily_count > 0 ? 20000 - res.daily_count : 20000
      setcounts(res.daily_count)
    })
  }

  //收藏 取消收藏
  const ChangeRate = (value: any) => {
    let params: any = null

    let iscollect: any = Databasetfavorites

    let mess: any = null

    if (!value.is_favorite) {
      params = {
        release_item_id: searchValue.release_item_id,
        data_ids: [value.id]
      }
      mess = '收藏成功'
    } else {
      params = { release_item_id: searchValue.release_item_id, data_id: value.id }
      iscollect = deleteDatabasetfavorites

      mess = '取消收藏'
    }

    iscollect(params).then((_res: any) => {
      message.success(mess)
      doRequest()
    })
  }

  //关联查询列表
  const DataBasetRelease = () => {
    DataBasetRelease_items({
      release_item_id: searchValue.release_item_id,
      page: 1,
      page_size: 9999
    }).then((res: any) => {
      setrelease_items(res.items)
    })
  }

  //关联数据
  function openModal(ids: any) {
    //判断是否是字符串
    if (typeof ids === 'string') {
      setAssociationid([ids])
    } else setAssociationid(ids)

    setisModalOpen1(true)

    DataBasetRelease()
  }

  //导出方法
  const setIsModalOpen = () => {
    if (selectedRowKeys.length > counts) {
      api.warning({
        message: '超过导出限制',
        description: `今日累计导出超过20000条，剩余${counts}条，请重新选择`
      })
      return
    }

    if (selectedRowKeys.length) {
      if (selectedRowKeys.length < 5000) EmailModalRef.current.showModal()
      if (selectedRowKeys.length > 5000 && selectedRowKeys.length < 10000) setModalOpen2(true)
      if (selectedRowKeys.length > 10000) {
        api.warning({
          message: '超过导出限制',
          description: `导出超过单次数量限制10000条，请重新选择`
        })
      }
      if (selectedRowKeys.length > 500) {
        api.warning({
          message: '超过导出限制',
          description: `导出超过单次数量500，请重新选择`
        })
      }
    } else {
      if (totalNumber > counts && counts !== 20000) {
        api.warning({
          message: '超过导出限制',
          description: `今日累计导出超过20000条，剩余${counts}条，请重新选择`
        })
      } else {
        if (totalNumber < 5000) EmailModalRef.current.showModal()
        if (totalNumber > 5000 && totalNumber < 10000) setModalOpen2(true)
        if (totalNumber > 10000) {
          api.warning({
            message: '超过导出限制',
            description: `导出超过单次数量限制10000，请重新选择`
          })
        }
      }
    }
  }

  // 导出提交
  const handleExport = (obj: any) => {
    const params: any = {
      columns: [],
      filename: obj.filename,
      query: {
        release_item_id: searchValue.release_item_id,
        ids: null,
        filters: [],
        page: 1,
        page_size: 100
      }
    }
    columns.map((item: any) => {
      if (columnsStateMap[item.dataIndex]?.show) {
        params.columns.push({
          field: item.dataIndex,
          name: item.title
        })
      }
    })

    if (searchValue?.relation) {
      params.query.relation = searchValue?.relation
    } else {
      params.query.relation = null
    }

    if (selectedRowKeys?.length) {
      params.query.ids = selectedRowKeys
    } else {
      params.query.filters = searchValue.filters.items
      params.query.keywords = Inputsearch
    }

    DataBasetexport(params).then((_res: any) => {
      let messages: any = `提交成功,请在${obj.Email}中查看导出结果`
      export_counts() //更新导出数量值
      if (selectedRowKeys.length) {
        if (selectedRowKeys.length > 5000 && selectedRowKeys.length < 10000) messages = `提交成功，请在个人中心中查看审核结果`
      } else {
        if (totalNumber > 5000 && totalNumber < 10000) messages = `提交成功，请在个人中心中查看审核结果`
      }
      message.success(messages)
      actionRef.current?.clearSelected()
      setselectedRowKeys([])
      setModalOpen2(false)
    })
  }

  //导出邮箱弹框确定
  const exportonok = () => {
    setModalOpen2(false)
    EmailModalRef.current.showModal()
  }

  const filters = (List: any) => {
    const arr: any = []
    List.forEach((item: any) => {
      if (item.available) {
        const obj: any = {}
        obj.title = item.comment
        obj.dataIndex = item.name
        obj.queryable = item.queryable
        obj.width = 300
        obj.render = (text: any) => {
          text = text && typeof text === 'object' ? JSON.stringify(text) : text
          return <Text ellipsis={{ tooltip: true }}>{typeof text === 'string' ? text : JSON.stringify(text)}</Text>
        }
        if (item.sort) {
          obj.sorter = true
          obj.sortDirections = ['descend', 'ascend']
        }
        arr.push(obj)
      }
    })
    return arr
  }

  //获取数据表头
  const Databasetitles = () => {
    if (!columnsChangeFlag) {
      return
    }
    Databasesort_ruleslist((res: any) => {
      //二维数组变成一维数组
      const sortlist = res.flat()
      Databasetitle(searchValue.release_item_id).then((res: any) => {
        res = res.filter((item: { available: any }) => item.available)
        res.sort((a: { queryable: number }, b: { queryable: number }) => b.queryable - a.queryable)
        const obj: any = {
          action: {
            disable: true,
            show: true,
            fixed: 'left',
            sorter: true
          }
        }
        res.forEach((item: any, index: any) => {
          obj[item.name] = {
            show: item.queryable ? true : false,
            fixed: !index ? 'left' : false,
            ellipsis: !index ? true : false
          }
        })
        setColumnsStateMap(obj)

        res.forEach((item: any) => {
          sortlist.forEach((_item1: any) => {
            if (item.name === _item1.field) {
              item.sort = true
            }
          })
        })
        setColumns(filters(res))
      })
    })
  }

  //获取表头排序
  const Databasesort_ruleslist = async (callBack: any) => {
    const arr: any = []
    const list = await Databasesort_rules({ id: searchValue.release_item_id, page: 1, page_size: 999 })
    list.items.forEach((item: any) => {
      if (item.type === 'time' || item.type === 'numeric') arr.push(item.config.fields)
    })
    callBack(arr)
  }

  //关闭关联数据的弹框清空弹框数据
  const onCancelModal = () => {
    setisModalOpen1(false)
    setAssociationid([]) //清空勾选的id
  }
  //储存该条数据 给关联弹框查询列表用
  const Changrelease_item = (e: any) => {
    // id: 关联数据项的id relation_id: 这条数据的id field:关联的字段 data_ids:选中左边列表的id
    const prevItems: any = {
      id: e.right_item.id,
      relation_id: e.right_item.id,
      field: e.right_field,
      data_ids: Associationid
    }
    success(prevItems)

    onCancelModal()
  }

  //勾选的回调
  const doSelect = (record: any, selected: any) => {
    if (selected) {
      setselectedRowKeys((prevState: any[]) => {
        prevState.push(record.id)
        return [...prevState]
      })
    } else {
      setselectedRowKeys((prevState: any[]) => {
        const index = prevState.findIndex((ele: any) => ele === record.id)
        prevState.splice(index, 1)
        return [...prevState]
      })
    }
  }

  //列表勾选的回调
  const rowSelection = {
    onChange: (_selectedRowKeys: any, _selectedRows: any, info: { type: any }) => {
      if (info.type === 'none') {
        setselectedRowKeys([])
      }
    },
    onSelect: doSelect,
    renderCell: (checked: boolean, record: any) => (
      <div className="flex items-center">
        <Tooltip placement="topLeft" title={checked ? '取消选中' : '选中'}>
          <Checkbox
            checked={checked}
            onChange={(e) => {
              doSelect(record, e.target.checked)
            }}
          />
        </Tooltip>
      </div>
    )
  }

  const PAGESIZE = 20

  const [totalNumber, settotalNumber] = useState(0)

  const [pagination, setPagination] = useImmer<any>({
    current: 1,
    pageSize: PAGESIZE
  })

  const addPage = () => {
    if (pagination?.current * pagination.pageSize < totalNumber) {
      setPagination((prev: { current: number }) => {
        prev.current++
      })
      setcolumnsChangeFlag(false)
    }
    settotalNumber(0)
  }
  const minusPage = () => {
    setPagination((prev: { current: number }) => {
      prev.current--
    })
    setcolumnsChangeFlag(false)
  }

  //sorter 列表sort功能 sortOrder代表升序asc还是降序desc

  const sorter = (sortOrder: any) => {
    let sorttype = null
    if (sortOrder.order === 'ascend') sorttype = `${sortOrder.columnKey}:asc`
    if (sortOrder.order === 'descend') sorttype = `${sortOrder.columnKey}:desc`
    sorterItem(sorttype)
  }

  //获取列表数据
  const doRequest = () => {
    return DatabaseList({
      page: pagination.current,
      page_size: pagination.pageSize,
      id: searchValue.release_item_id,
      keywords: Inputsearch,
      filters: searchValue.filters.items,
      ids: searchValue.ids ? searchValue.ids : null,
      relation: searchValue.relation ?? null,
      sort: searchValue.sort ?? null
    })
      .then((res) => {
        setData(
          res.items.map((item: any, index: number) => {
            Object.keys(item).forEach((key) => {
              handleTableShowDate(item, key)
            })
            return { ...item, index }
          })
        )
        settotalNumber(res.total)

        return res
      })
      .finally(() => {})
  }

  useEffect(() => {
    export_counts()
  }, [])

  useEffect(() => {
    searchValue.release_item_id && Databasetitles()
  }, [searchValue.release_item_id])

  useEffect(() => {
    if (hasInit) {
      doRequest()
      setcolumnsChangeFlag(true)
    }
  }, [searchValue, pagination])

  useImperativeHandle(
    ref,
    () => {
      return {
        showModal() {
          doRequest()
          Databasetitles()
        },
        getList() {
          doRequest()
        },
        //页面重置
        resizeTo() {
          setPagination((prevPagi: any) => {
            prevPagi.current = 1
            prevPagi.pageSize = PAGESIZE
          })
        },
        resizeExport_counts() {
          export_counts()
        },
        clearsetselectedRowKeys() {
          setselectedRowKeys([])
        }
      }
    },
    [Inputsearch, searchValue]
  )
  const permissions = getItem(PERMISSIONS) || []
  return (
    <div className="w-100% h-100%">
      <div className="flex justify-between items-center">
        <div className="flex items-center">
          <div className="mr-10px">{`共${totalNumber}`}条</div>
          <Button className="mr-10px" type="primary" onClick={minusPage} disabled={pagination.current === 1}>
            上一页
          </Button>
          <div className="mr-20px">{`${(pagination.current - 1) * pagination.pageSize + 1} - ${pagination.current * pagination.pageSize}`}条</div>
          <Button type="primary" onClick={addPage} disabled={pagination.current * pagination.pageSize >= totalNumber}>
            下一页
          </Button>
        </div>
        <div className="m-10px flex items-center">
          <div>
            {selectedRowKeys.length > 1 ? (
              <Button className="mr-50px mb-16px" type="primary" onClick={() => openModal(selectedRowKeys)}>
                批量关联查询
              </Button>
            ) : null}
          </div>
          {permissions.includes('sg.export.limit.20000') && (
            <div className="flex flex-col">
              {contextHolder}
              <Button type="primary" onClick={setIsModalOpen}>
                {selectedRowKeys.length ? `导出${selectedRowKeys.length}` : '全部导出'}
              </Button>
              <div>今日还能导出{counts}条</div>
            </div>
          )}
        </div>
      </div>

      <HsAdminProTable
        id="RelationList-table"
        rowSelection={{
          hideSelectAll: true,
          type: 'checkbox',
          selectedRowKeys,
          ...rowSelection
        }}
        columns={[baseConfig, ...columns]}
        rowKey="id"
        dataSource={data}
        onChange={(_a: any, _b: any, sortOrder: any) => sorter(sortOrder)}
        columnsState={{ value: columnsStateMap, onChange: setColumnsStateMap }}
        pagination={false}
        scroll={{ x: 1500, y: 650 }}
        options={{
          setting: {
            checkedReset: false
          }
        }}
      />

      <Modal title={'关联查询（查询该条数据关联的其他数据）'} open={isModalOpen1} onCancel={onCancelModal} footer={null}>
        <div className="pl-40px">
          {release_items.map((item: any) => (
            <div key={item.id} className="mb-10px text-blue cursor-pointer" onClick={() => Changrelease_item(item)}>
              {item.right_item.data_item_product.name}
            </div>
          ))}
        </div>
      </Modal>

      <ServerEmailModal ref={EmailModalRef} success={handleExport} title={'导出数据'}></ServerEmailModal>
      <Modal
        title={'单次导出超出5000条，需要通过审批才能导出，是否继续？'}
        open={isModalOpen2}
        onCancel={() => setModalOpen2(false)}
        onOk={exportonok}></Modal>
    </div>
  )
}
export default memo(forwardRef(RelationList))
